package com.ideal.manage.esms.service.alarm;

import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.alarm.Alarm;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseResultInfo;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.compoment.GetAlarmHitsComponent;
import com.ideal.manage.esms.repository.alarm.AlarmRepository;
import com.ideal.manage.esms.repository.diagnostic.DiagnoseResultInfoRepository;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.monitor.UnitCellDataScanBaseRepository;
import com.ideal.manage.esms.repository.project.AlarmInfoRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import com.ideal.manage.esms.service.project.EquipmentManageService;
import com.ideal.manage.esms.util.DateBtnUtil;
import com.ideal.manage.esms.util.ElasticsearchUtils;
import com.ideal.manage.esms.util.HttpRequests;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AlarmService {
    @Autowired
    private AlarmRepository alarmRepository;
    @Autowired
    private EquipmentManageRepository equipmentManageRepository;
    @Autowired
    private AlarmInfoRepository alarmInfoRepository;
    @Autowired
    private EquipmentManageService equipmentManageService;
    @Autowired
    private ProjectManageRepository projectManageRepository;
    @Autowired
    private GetAlarmHitsComponent getAlarmHitsComponent;
    @Autowired
    private DiagnoseResultInfoRepository diagnoseResultInfoRepository;

    @Autowired
    private UnitCellDataScanBaseRepository unitCellDataScanBaseRepository;

    /**
     * 分页查询过程报警内容
     *
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<Alarm> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<Alarm> page = alarmRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<Alarm> alarms = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(alarms);
        pageDto.setTotal(total);
        return pageDto;
    }

   /* //查询状态
    public List<Alarm> findAlarmByState() {
        List<Alarm> alarmByState = alarmRepository.findAlarmByState();
        return alarmByState;
    }

    //查询全部信息
    public List<Alarm> findAlarmAll() {
        List<Alarm> all = alarmRepository.findAll();
        return all;
    }*/

    //保存备注
    public void save(String id, String operateContent) {
        Alarm alarmData = alarmRepository.findOne(id);
        Alarm alarm = new Alarm();
        alarm.setId(id);
        alarm.setEquipmentName(alarmData.getEquipmentName());
        alarm.setAlarmContent(alarmData.getAlarmContent());
        alarm.setAlarmLev(alarmData.getAlarmLev());
        alarm.setSource(alarmData.getSource());
        alarm.setDealIdea(alarmData.getDealIdea());
        alarm.setState(alarmData.getState());
        alarm.setOperateTime(new Date());
        alarm.setOperateContent(operateContent);
        alarm.setCreateTime(alarmData.getCreateTime());
        alarm.setIsValid(alarmData.getIsValid());
        alarmRepository.save(alarm);

    }

    //查找id
    public Alarm findAlarmById(String id) {
        Alarm alarm = alarmRepository.findOne(id);
        return alarm;
    }

    //通过id更新状态("作废")
    public void updateState(String id) {
        Alarm oneData = alarmRepository.findOne(id);
        Alarm alarm = new Alarm();
        alarm.setId(id);
        alarm.setEquipmentName(oneData.getEquipmentName());
        alarm.setAlarmContent(oneData.getAlarmContent());
        alarm.setAlarmLev(oneData.getAlarmLev());
        alarm.setSource(oneData.getSource());
        alarm.setDealIdea(oneData.getDealIdea());
        alarm.setState(3);
        alarm.setOperateTime(new Date());
        alarm.setOperateContent(oneData.getOperateContent());
        alarm.setCreateTime(oneData.getCreateTime());
        alarm.setIsValid(oneData.getIsValid());
        alarmRepository.save(alarm);


    }

    //通过id更新状态("处理状态")
    public void updateStateCl(String id) {
        Alarm oneData = alarmRepository.findOne(id);
        Alarm alarm = new Alarm();
        alarm.setId(id);
        alarm.setEquipmentName(oneData.getEquipmentName());
        alarm.setAlarmContent(oneData.getAlarmContent());
        alarm.setAlarmLev(oneData.getAlarmLev());
        alarm.setSource(oneData.getSource());
        alarm.setDealIdea(oneData.getDealIdea());
        alarm.setState(2);
        alarm.setOperateTime(new Date());
        alarm.setOperateContent(oneData.getOperateContent());
        alarm.setCreateTime(oneData.getCreateTime());
        alarm.setIsValid(oneData.getIsValid());
        alarmRepository.save(alarm);
    }

    /**
     * 报警信息从es中入库
     * 报文数据解释:
     * 1.一条报文中包含多条信息
     * 2.报文中包含的多条信息中有多数的都是对应的没数据信息(0.0)
     * 逻辑:
     * 1.通过调用es的接口拿到相对应的报文数据
     * 2.将拿到的数据进行处理过滤
     * 3.入库
     */
    public void getAlarmInfo() {
        String eName = "";
        SearchHit[] alarmHits = null;
        List alarmLists = new ArrayList();
        Map<String, String> alarmEname = new HashMap();
        //获取所有的项目的ip
        List<String> ips = projectManageRepository.findByPip();
        //报警过程找到适用对象(有效的设备)
        List<EquipmentManage> equipmentManageList = equipmentManageRepository.findAllEquipmentsCode(ips);
        //获取设备的唯一标识(code)
        String macid = null;
        for (EquipmentManage eq : equipmentManageList) {
            if (eq.getCode() == null || eq.getCode() == "") {
                continue;
            }
            if (eq.getCode().length() > 9) {
                String codes = eq.getCode().substring(eq.getCode().indexOf("#") + 1, eq.getCode().length()) + "Volt";
                alarmEname.put(codes, eq.getName());
                macid = eq.getCode().substring(0, eq.getCode().indexOf("#"));
                alarmLists.add(codes);
            }
            alarmEname.put(eq.getCode(), eq.getName());
        }

        /**
         * 已结改为task，5分钟一次
         */
        //getAlarmHitsComponent.getAlarmHits();

        /**
         //设置当前的时间的毫秒数
         Calendar calendar = Calendar.getInstance();
         calendar.set(Calendar.MILLISECOND, 0);
         Long time = calendar.getTimeInMillis() - 10000L;
         //给出接口查询名
         alarmHits = ElasticsearchUtils.getAlarmHits(macid, time);

         //判断返回的数据是否空,不为空则分析过滤入库
         if (alarmHits == null) {
         return;
         } else {
         //遍历入库
         for (SearchHit aHits : alarmHits) {
         //创建报警管理对象,入库准备
         Alarm alarm = new Alarm();
         Map map = aHits.getSourceAsMap();
         //入库判断
         if (map.containsKey("AlarmLevel")) {
         String level = map.get("AlarmLevel").toString();
         String levelAlarm = level.substring(0, 1);
         //告警等级入库
         alarm.setAlarmLev(levelAlarm);
         //开始时间入库
         long startTime = Long.parseLong(map.get("time").toString());
         //long类型时间处理
         Date date = simpleFormatDate(startTime);
         alarm.setCreateTime(date);
         //设备CANID
         String equipmentId = map.get("messageId").toString();
         //存入equipmentId
         alarm.setEquipmentId(equipmentId);
         //存入equipmentName
         //判断code是否相等
         String name = map.get("macid").toString();
         for (Map.Entry<String, String> entry : alarmEname.entrySet()) {
         String value = entry.getValue();
         if (name.equals(entry.getKey())) {
         eName = entry.getValue();
         break;
         }
         }

         //报警类容
         //电池单体
         for (int i = 1; i <= 100; i++) {
         if (i < 10) {
         if (map.containsKey("Cell_0" + i + "_Volt") && map.get("Cell_0" + i + "_Volt") != "0.0") {
         alarm.setAlarmContent("单体电压0" + i);
         alarm.setSource("BMS");
         break;
         }
         }
         if (i >= 10) {
         if (map.containsKey("Cell_" + i + "_Volt") && map.get("Call_" + i + "_Volt") != "0.0") {
         alarm.setAlarmContent("单体电压" + i);
         alarm.setSource("BMS");
         break;
         }
         }
         }
         //温度
         int o = 0;
         for (int j = 1; j <= 10; j++) {
         for (int k = 1; k <= 8; k++) {
         o++;
         if (map.containsKey("Bsu" + j + "Temp" + k) && map.get("Bsu" + j + "Temp" + k) != "0.0") {
         alarm.setAlarmContent("电池温度0" + o);
         alarm.setSource("BMS");
         break;
         }
         }
         }
         //动力电池总电压
         if (map.containsKey("SysVolt") && map.get("SysVolt") != "0.0") {
         alarm.setAlarmContent("动力电池总电压");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("SysCurr") && map.get("SysCurr") != "0.0") {
         //动力电池总电流
         alarm.setAlarmContent("动力电池总电流");
         alarm.setEquipmentName(eName);
         alarm.setSource("PCS");
         } else if (map.containsKey("SOC") && map.get("SOC") != "0.0") {
         //SOC
         alarm.setAlarmContent("动力电池SOC");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("SOH") && map.get("SOH") != "0.0") {
         //SOH
         alarm.setAlarmContent("动力电池SOH");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_CellOV") && map.get("Alarm_CellOV") != "0.0") {
         alarm.setAlarmContent("单体过压");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_CellUV") && map.get("Alarm_CellUV") != "0.0") {
         alarm.setAlarmContent("单体欠压");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_CellOT") && map.get("Alarm_CellOT") != "0.0") {
         alarm.setAlarmContent("单体高温");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_CellUT") && map.get("Alarm_CellUT") != "0.0") {
         alarm.setAlarmContent("单体低温");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_LBK") && map.get("Alarm_LBK") != "0.0") {
         alarm.setAlarmContent("单体电压断线");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_TBK") && map.get("Alarm_TBK") != "0.0") {
         alarm.setAlarmContent("单体温度断线");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatDV") && map.get("Alarm_BatDV") != "0.0") {
         alarm.setAlarmContent("单体压差过大");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatDT") && map.get("Alarm_BatDT") != "0.0") {
         alarm.setAlarmContent("单体温差过大");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatOV") && map.get("Alarm_BatOV") != "0.0") {
         alarm.setAlarmContent("电池组过压");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatUV") && map.get("Alarm_BatUV") != "0.0") {
         alarm.setAlarmContent("电池组欠压");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatOC") && map.get("Alarm_BatOC") != "0.0") {
         alarm.setAlarmContent("电池组SOC过高");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_BatUC") && map.get("Alarm_BatUC") != "0.0") {
         alarm.setAlarmContent("电池组SOC过低");
         alarm.setEquipmentName(eName);
         alarm.setSource("BMS");
         } else if (map.containsKey("Alarm_CHRG_OCS") && map.get("Alarm_CHRG_OCS") != "0.0") {
         alarm.setAlarmContent("稳态充电过流");
         alarm.setEquipmentName(eName);
         alarm.setSource("PCS");
         } else if (map.containsKey("Alarm_DSCH_OCS") && map.get("Alarm_DSCH_OCS") != "0.0") {
         alarm.setAlarmContent("稳态放电过流");
         alarm.setEquipmentName(eName);
         alarm.setSource("PCS");
         } else if (map.containsKey("Alarm_CHRG_OCT") && map.get("Alarm_CHRG_OCT") != "0.0") {
         alarm.setAlarmContent("瞬态充电过流");
         alarm.setEquipmentName(eName);
         alarm.setSource("PCS");
         } else if (map.containsKey("Alarm_DSCH_OCT") && map.get("Alarm_DSCH_OCT") != "0.0") {
         alarm.setAlarmContent("瞬态放电过流");
         alarm.setEquipmentName(eName);
         alarm.setSource("PCS");
         } else if (map.containsKey("Alarm_BSU_OFFLINE") && map.get("Alarm_BSU_OFFLINE") != "0.0") {
         alarm.setAlarmContent("BSU离线");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_BSU_FAULT") && map.get("Alarm_BSU_FAULT") != "0.0") {
         alarm.setAlarmContent("BSU均衡故障");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_LEAK_OC") && map.get("Alarm_LEAK_OC") != "0.0") {
         alarm.setAlarmContent("漏电流超限");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_PrechrgFail") && map.get("Alarm_PrechrgFail") != "0.0") {
         alarm.setAlarmContent("预充失败");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_AuxFail") && map.get("Alarm_AuxFail") != "0.0") {
         alarm.setAlarmContent("继电器故障");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_Bmuil") && map.get("Alarm_Bmuil") != "0.0") {
         alarm.setAlarmContent("BMU故障");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_Vcu_Offline") && map.get("Alarm_Vcu_Offline") != "0.0") {
         alarm.setAlarmContent("VCU通信超时");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_HV_Fail") && map.get("Alarm_HV_Fail") != "0.0") {
         alarm.setAlarmContent("电池高压异常");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         } else if (map.containsKey("Alarm_Hall_Break") && map.get("Alarm_Hall_Break") != "0.0") {
         alarm.setAlarmContent("霍尔断线");
         alarm.setEquipmentName(eName);
         alarm.setSource("诊断");
         }


         // 处理建议意见
         //入库处理意见建议
         if (levelAlarm == "1") {
         alarm.setDealIdea("建议关闭系统");
         } else if (levelAlarm == "2") {
         alarm.setDealIdea("建议通知工程师处理");
         } else if (levelAlarm == "3") {
         alarm.setDealIdea("建议现场处理");
         } else if (levelAlarm == "4") {
         alarm.setDealIdea("建议跟踪观察");
         } else {
         alarm.setDealIdea("无法根据报警类容给出建议");
         }
         alarm.setState(1);
         alarm.setIsValid(1);
         alarm.setOperateTime(date);
         alarmRepository.save(alarm);
         }

         }
         }**/

    }


    /**
     * 根据项目id找到所有的电池包故障信息
     *
     * @param id
     * @return
     */
    public List<Alarm> findAlarmEquipment(String id) {
        List<Alarm> alarmList = new ArrayList<>();
        List<EquipmentManage> equipmentManageList = equipmentManageService.findEquipments(id, "2");
        for (EquipmentManage equipmentManage : equipmentManageList) {
            List<Alarm> alarms = alarmRepository.findAlarmById(equipmentManage.getId());
            alarmList.addAll(alarms);
        }
        return alarmList;
    }


    public JSONObject findLevelByAlarm(List<Alarm> alarms) {
        JSONObject jsonObject = new JSONObject();
        Integer level1 = 0;
        Integer level2 = 0;
        Integer level3 = 0;
        Integer level4 = 0;

        for (Alarm alarm : alarms) {
            if ("1.0".equals(alarm.getAlarmLev())) {
                level1 += 1;
            } else if ("2.0".equals(alarm.getAlarmLev())) {
                level2 += 1;
            } else if ("3.0".equals(alarm.getAlarmLev())) {
                level3 += 1;
            } else if ("4.0".equals(alarm.getAlarmLev())) {
                level4 += 1;
            }
        }
        jsonObject.put("level1", level1);
        jsonObject.put("level2", level2);
        jsonObject.put("level3", level3);
        jsonObject.put("level4", level4);

        return jsonObject;
    }

    /**
     * 月报中的报警等级的集合(饼图)
     *
     * @param alarms
     * @return
     */
    public List<JSONObject> findLevelByAlarmMonth(List<Alarm> alarms) {

        List<JSONObject> lists = new ArrayList();
        Integer level1 = 0;
        Integer level2 = 0;
        Integer level3 = 0;
        Integer level4 = 0;
        for (Alarm alarm : alarms) {
            if ("1".equals(alarm.getAlarmLev())) {
                level1 += 1;
            } else if ("2".equals(alarm.getAlarmLev())) {
                level2 += 1;
            } else if ("3".equals(alarm.getAlarmLev())) {
                level3 += 1;
            } else if ("4".equals(alarm.getAlarmLev())) {
                level4 += 1;
            }

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "一级");
        jsonObject.put("value", level1);
        lists.add(jsonObject);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name", "二级");
        jsonObject2.put("value", level2);
        lists.add(jsonObject2);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("name", "三级");
        jsonObject3.put("value", level3);
        lists.add(jsonObject3);
        JSONObject jsonObject4 = new JSONObject();
        jsonObject4.put("name", "四级");
        jsonObject4.put("value", level4);
        lists.add(jsonObject4);
        System.out.println(lists);
        return lists;
    }

/********************************按钮筛选******************************/
    /**
     * 条件查询
     *
     * @return
     */
    public PageDto findByToday(HttpServletRequest request, List<String> condition, int pageNum) throws ParseException {
        //创建条件查询
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        if (condition.size() == 6) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //自定义
            //获取开始时间
            String startTime = condition.get(0);
            Date start = dateFormat.parse(startTime);
            String endTime = condition.get(1);
            Date end = dateFormat.parse(endTime);
            SpecificationOperator operator = new SpecificationOperator("createTime", start, "GT");
            SpecificationOperator operator2 = new SpecificationOperator("createTime", end, "LT");
            operators.add(operator);
            operators.add(operator2);
            if (condition.contains("rank")) {
                SpecificationOperator operatorr = new SpecificationOperator("alarmLev", "0", "GT");
                operators.add(operatorr);

            }
            if (condition.contains("one")) {
                SpecificationOperator operatoro = new SpecificationOperator("alarmLev", "1", "EQ");
                operators.add(operatoro);

            }
            if (condition.contains("two")) {
                SpecificationOperator operatort = new SpecificationOperator("alarmLev", "2", "EQ");
                operators.add(operatort);

            }
            if (condition.contains("three")) {
                SpecificationOperator operatorte = new SpecificationOperator("alarmLev", "3", "EQ");
                operators.add(operatorte);
            }
            if (condition.contains("four")) {
                SpecificationOperator operatorf = new SpecificationOperator("alarmLev", "4", "EQ");
                operators.add(operatorf);

            }
            if (condition.contains("status")) {
                SpecificationOperator operatorstat = new SpecificationOperator("state", "0", "GT");
                operators.add(operatorstat);
            }
            if (condition.contains("unconfirm")) {
                SpecificationOperator operatorsu = new SpecificationOperator("state", "1", "EQ");
                operators.add(operatorsu);
            }
            if (condition.contains("affirm")) {
                SpecificationOperator operatora = new SpecificationOperator("state", "2", "EQ");
                operators.add(operatora);

            }
            if (condition.contains("processed")) {
                SpecificationOperator operatorp = new SpecificationOperator("state", "3", "EQ");
                operators.add(operatorp);

            }
            if (condition.contains("destroy")) {
                SpecificationOperator operatord = new SpecificationOperator("state", "3", "EQ");
                operators.add(operatord);
            }
            if (condition.contains("BMS")) {
                SpecificationOperator operatorsour = new SpecificationOperator("source", "BMS", "EQ");
                operators.add(operatorsour);

            }
            if (condition.contains("PCS")) {
                SpecificationOperator operatorsour = new SpecificationOperator("source", "PCS", "EQ");
                operators.add(operatorsour);

            }
            if (condition.contains("diagnostic")) {
                SpecificationOperator operatorsour = new SpecificationOperator("source", "诊断", "EQ");
                operators.add(operatorsour);
            }
            SpecificationOperator operatorIs = new SpecificationOperator("isValid", "1", "EQ");
            operators.add(operatorIs);
            Sort sort = new Sort(Sort.Direction.DESC, "createTime");
            MySpecification<Alarm> mySpecifications = new MySpecification<>(operators);
            Pageable pageable = new PageRequest(pageNum, 10, sort);
            Page<Alarm> page = alarmRepository.findAll(mySpecifications, pageable);
            //设置PageDto
            List<Alarm> alarms = page.getContent();
            long total = page.getTotalElements();
            PageDto pageDto = new PageDto();
            pageDto.setRows(alarms);
            pageDto.setTotal(total);
            return pageDto;
        } else {
            for (int i = 0; i < condition.size(); i++) {
                //筛选按钮时间
                if (condition.get(i).equals("createTime")) {
                    //调用今日方法
                    List<Date> dateLists = DateBtnUtil.today();
                    Date today = dateLists.get(0);
                    Date tomorrow = dateLists.get(1);
                    SpecificationOperator operatorg = new SpecificationOperator("createTime", today, "GT");
                    SpecificationOperator operatorl = new SpecificationOperator("createTime", tomorrow, "LT");
                    operators.add(operatorg);
                    operators.add(operatorl);
                    continue;
                } else if (condition.get(i).equals("yestoday")) {
                    //调用昨天处理的方法
                    List<Date> dateLists = DateBtnUtil.yestoday();
                    Date today = dateLists.get(0);
                    Date yestoday = dateLists.get(1);
                    SpecificationOperator operatorg = new SpecificationOperator("createTime", today, "GT");
                    SpecificationOperator operatorl = new SpecificationOperator("createTime", yestoday, "LT");
                    operators.add(operatorg);
                    operators.add(operatorl);
                    continue;
                } else if (condition.get(i).equals("week")) {
                    //调用本周的处理方法
                    List<Date> week = DateBtnUtil.week();
                    Date monDay = week.get(0);
                    Date sunDay = week.get(1);
                    SpecificationOperator operatorg = new SpecificationOperator("createTime", monDay, "GT");
                    SpecificationOperator operatorl = new SpecificationOperator("createTime", sunDay, "LT");
                    operators.add(operatorg);
                    operators.add(operatorl);
                    continue;
                } else if (condition.get(i).equals("month")) {
                    //调用本月处理方法
                    List<Date> month = DateBtnUtil.month();
                    Date mothFirst = month.get(0);
                    Date mothLast = month.get(1);
                    SpecificationOperator operatorg = new SpecificationOperator("createTime", mothFirst, "GT");
                    SpecificationOperator operatorl = new SpecificationOperator("createTime", mothLast, "LT");
                    operators.add(operatorg);
                    operators.add(operatorl);
                    continue;
                } else if (condition.get(i).equals("rank")) {
                    SpecificationOperator operator = new SpecificationOperator("alarmLev", "0", "GT");
                    operators.add(operator);
                    continue;
                } else if (condition.get(i).equals("one")) {
                    SpecificationOperator operator = new SpecificationOperator("alarmLev", "1.0", "EQ");
                    operators.add(operator);
                    continue;
                } else if (condition.get(i).equals("two")) {
                    SpecificationOperator operator = new SpecificationOperator("alarmLev", "2.0", "EQ");
                    operators.add(operator);
                    continue;
                } else if (condition.get(i).equals("three")) {
                    SpecificationOperator operator = new SpecificationOperator("alarmLev", "3.0", "EQ");
                    operators.add(operator);
                    continue;
                } else if (condition.get(i).equals("four")) {
                    SpecificationOperator operator = new SpecificationOperator("alarmLev", "4.0", "EQ");
                    operators.add(operator);
                    continue;
                } else if (condition.get(i).equals("status")) {
                    SpecificationOperator operatorstat = new SpecificationOperator("state", "0", "GT");
                    operators.add(operatorstat);
                    continue;
                } else if (condition.get(i).equals("unconfirm")) {
                    SpecificationOperator operatorstat = new SpecificationOperator("state", "1", "EQ");
                    operators.add(operatorstat);
                    continue;
                } else if (condition.get(i).equals("affirm")) {
                    SpecificationOperator operatorstat = new SpecificationOperator("state", "2", "EQ");
                    operators.add(operatorstat);
                    continue;
                } else if (condition.get(i).equals("processed")) {
                    SpecificationOperator operatorstat = new SpecificationOperator("state", "3", "EQ");
                    operators.add(operatorstat);
                    continue;
                } else if (condition.get(i).equals("destroy")) {
                    SpecificationOperator operatorstat = new SpecificationOperator("state", "3", "EQ");
                    operators.add(operatorstat);
                    continue;
                } else if (condition.get(i).equals("source")) {
                    continue;
                } else if (condition.get(i).equals("BMS")) {
                    SpecificationOperator operatorsour = new SpecificationOperator("source", "BMS", "EQ");
                    operators.add(operatorsour);
                    continue;
                } else if (condition.get(i).equals("PCS")) {
                    SpecificationOperator operatorsour = new SpecificationOperator("source", "PCS", "EQ");
                    operators.add(operatorsour);
                    continue;
                } else if (condition.get(i).equals("diagnostic")) {
                    SpecificationOperator operatorsour = new SpecificationOperator("source", "诊断", "EQ");
                    operators.add(operatorsour);
                }
            }
            SpecificationOperator operator = new SpecificationOperator("isValid", "1", "EQ");
            operators.add(operator);
            Sort sort = new Sort(Sort.Direction.DESC, "createTime");
            MySpecification<Alarm> mySpecifications = new MySpecification<>(operators);
            Pageable pageable = new PageRequest(pageNum, 10, sort);
            Page<Alarm> page = alarmRepository.findAll(mySpecifications, pageable);
            //设置PageDto
            List<Alarm> alarms = page.getContent();
            long total = page.getTotalElements();
            PageDto pageDto = new PageDto();
            pageDto.setRows(alarms);
            pageDto.setTotal(total);
            return pageDto;
        }

    }

    /**
     * 月报报警信息展示
     *
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findMothData(int pageNum, HttpServletRequest request) throws ParseException {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        //时间范围
        List<Date> month = DateBtnUtil.month();
        Date mothFirst = month.get(0);
        Date mothLast = month.get(1);
        SpecificationOperator oneDay = new SpecificationOperator("createTime", mothFirst, "GT");
        SpecificationOperator lastDay = new SpecificationOperator("createTime", mothLast, "LT");
        operators.add(isValid);
        operators.add(oneDay);
        operators.add(lastDay);
        MySpecification<Alarm> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 2, sort);
        Page<Alarm> page = alarmRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<Alarm> alarms = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(alarms);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 年报报警信息展示
     *
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findYearReport(int pageNum, HttpServletRequest request) throws ParseException {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        //时间范围
        Date beginyear = DateBtnUtil.getBeginDayOfYear();
        Date endYear = DateBtnUtil.getEndDayOfYear();
        SpecificationOperator oneDay = new SpecificationOperator("createTime", beginyear, "GT");
        SpecificationOperator lastDay = new SpecificationOperator("createTime", endYear, "LT");
        operators.add(isValid);
        operators.add(oneDay);
        operators.add(lastDay);
        MySpecification<Alarm> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 2, sort);
        Page<Alarm> page = alarmRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<Alarm> alarms = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(alarms);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 报警前后 10s soc
     *
     * @param id
     * @return
     */
    public Map<String, Object> getAlarmSoc(String id, String time) throws ParseException {
        //找到对应的设备的唯一标识
        // String macid = equipmentManageRepository.findByMacid(id);
        List<Date> dates = simpleDateFormat(time);
        Date startTime = dates.get(0);
        Date endTime = dates.get(1);
        //查询 诊断结果表取出对应的值
        JSONObject jsonObject = new JSONObject();
        String value = "0.0";
        String name;
        List<DiagnoseResultInfo> diagnoseResultInfos = diagnoseResultInfoRepository.findBySoc(id, startTime, endTime, "soc");
        for (int i = 1; i < 21; i++) {
            for (DiagnoseResultInfo diag : diagnoseResultInfos) {
                if (diag.getResultVal() != null) {
                    value = diag.getResultVal();
                    continue;
                }

            }
            name = String.valueOf(i);
            jsonObject.put(name, value);

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("jsonObject", jsonObject);

        return resultMap;
    }

    /**
     * 报警总电压
     *
     * @param id
     * @param time
     * @return
     */
    public Map<String, Object> getAlarmBattery(String id, String time) throws ParseException {
        String macid = equipmentManageRepository.findByMacid(id);
        List<Date> dates = simpleDateFormat(time);
        Date startTime = dates.get(0);
        Date endTime = dates.get(1);

        SearchHit[] batterys = ElasticsearchUtils.getBatterys(macid, startTime, endTime);

        Map<String, Object> source = new HashMap();

        for (SearchHit searchHit : batterys) {
            source.putAll(searchHit.getSourceAsMap());
        }


        JSONObject jsonBattery = new JSONObject();

        Float value = 0.0F;
        String name;
        for (int i = 1; i < 21; i++) {
            for (Map.Entry<String, Object> map : source.entrySet()) {
                if (map.getKey().equals("BatVoltage")) {
                    value = Float.valueOf(map.getValue().toString());
                }

                continue;
            }

            name = String.valueOf(i);
            jsonBattery.put(name, value);
            value = 0.0F;

        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("jsonBattery", jsonBattery);
        return resultMap;
    }

    /**
     * 报警电流
     *
     * @param id
     * @param time
     * @return
     */
    public Map<String, Object> getAlarmElectricity(String id, String time) throws ParseException {
        String macid = equipmentManageRepository.findByMacid(id);
        List<Date> dates = simpleDateFormat(time);
        Date startTime = dates.get(0);
        Date endTime = dates.get(1);

        SearchHit[] batterys = ElasticsearchUtils.getBatterys(macid, startTime, endTime);

        Map<String, Object> source = new HashMap();

        for (SearchHit searchHit : batterys) {
            source.putAll(searchHit.getSourceAsMap());
        }


        JSONObject jsonElectricity = new JSONObject();

        Float value = 0.0F;
        String name;
        for (int i = 1; i < 21; i++) {
            for (Map.Entry<String, Object> map : source.entrySet()) {
                if (map.getKey().equals("BatCurrent")) {
                    value = Float.valueOf(map.getValue().toString());
                }

                continue;
            }

            name = String.valueOf(i);
            jsonElectricity.put(name, value);
            value = 0.0F;

        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("jsonElectricity", jsonElectricity);
        return resultMap;
    }

    /**
     * 时间格式化
     *
     * @param time
     * @return
     * @throws ParseException
     */
    public List<Date> simpleDateFormat(String time) throws ParseException {
        List<Date> sdf = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long end = simpleDateFormat.parse(time).getTime();
        long start = end - 20000L;
        Date startTime = simpleDateFormat.parse(simpleDateFormat.format(new Date(start)));
        Date endTime = simpleDateFormat.parse(time);
        sdf.add(startTime);
        sdf.add(endTime);
        return sdf;
    }
}
